<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket客户端</title>
    <script>
        var socket;
        // 判断当前浏览器是否支持 WebSocket 编程
        if (!window.WebSocket) {
            alert("当前浏览器不支持websocket");
        } else {
            //有鉴权就必须要参数
            socket = new WebSocket("ws://localhost:8089/hello?token=a7f324be2fb");
            //socket = new WebSocket("ws://localhost:8089/hello");
            // 把服务器回复的消息回显
            socket.onmessage = function(eval) {
                var widget = document.getElementById("responseText");
                widget.value = widget.value + "\n" + eval.data;
            }
            // 连接服务器成功
            socket.onopen = function(eval) {
                console.log(eval);
                var widget = document.getElementById("responseText");
                widget.value = "连接开启了";
            }
            // 连接关闭了
            socket.onclose = function(eval) {
                var widget = document.getElementById("responseText");
                widget.value = eval.value + "\n" + "连接关闭了";
            }
        }
        // 发送消息到服务器
        function send(msg) {
            if(!window.socket) return ;
            if (socket.readyState == WebSocket.OPEN) {
                // 通过socket 发送消息
                socket.send(msg);
            } else {
                alert("连接没有开启");
            }
        }
    </script>
</head>
<body>
<form onsubmit="return false">
    <textarea id="message" style="height:300px; width:300px"></textarea>
    <input type="button" value="发送消息" onclick="send(this.form.message.value)">
    <textarea id="responseText" style="height:300px; width:300px"></textarea>
    <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
</form>
</body>
</html>